package com.jule.teenpatti.game.network.protocol.reqs;

import JoloProtobuf.GameSvr.JoloGame;
import com.jule.core.common.log.LoggerUtils;
import com.jule.core.jedis.StoredObjManager;
import com.jule.teenpatti.base.bean.ItemConfigBean;
import com.jule.teenpatti.base.bean.ItemType;
import com.jule.teenpatti.base.dao.bean.User;
import com.jule.teenpatti.base.enums.ErrorCodeEnum;
import com.jule.teenpatti.base.enums.GameConst;
import com.jule.teenpatti.base.enums.RedisConst;
import com.jule.teenpatti.game.play.TableUtil;
import com.jule.teenpatti.game.service.ProductionService;
import com.jule.teenpatti.log.service.LogReasons;
import com.jule.teenpatti.game.dao.DBUtil;
import com.jule.teenpatti.game.dao.bean.GiftHistoryModel;
import com.jule.teenpatti.game.model.PlayerInfo;
import com.jule.teenpatti.game.network.protocol.ClientReq;
import com.jule.teenpatti.game.network.protocol.acks.JoloGame_GiveGiftsAck_50052;
import com.jule.teenpatti.game.play.AbstractTable;
import com.jule.teenpatti.game.service.LogService;
import com.jule.teenpatti.game.service.TableService;
import com.jule.teenpatti.game.utils.log.TableLogUtil;
import com.jule.teenpatti.game.vavle.notice.NoticeBroadcastMessages;
import io.netty.buffer.ByteBuf;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;

@Slf4j
public class JoloGame_GiveGiftsReq_50052 extends ClientReq {
    private long time;

    public JoloGame_GiveGiftsReq_50052(int functionId) {
        super(functionId);
    }

    private JoloGame.JoloGame_GiveGiftsReq req;

    @Override
    public void readPayLoadImpl(ByteBuf buf) throws Exception {
        time = System.currentTimeMillis();
        byte[] blob = new byte[buf.readableBytes()];
        buf.readBytes(blob);
        req = JoloGame.JoloGame_GiveGiftsReq.parseFrom(blob);
        AbstractTable table = TableService.getInstance().getTable(header.gameId + "", req.getRoomId(), req.getTableId());
        if (null != table) {
            this.setTable(table);
        } else {
            log.error("桌子不存在,roomId->" + req.getRoomId() + ", tableId->" + req.getTableId());
        }
    }

    @Override
    public void processImpl() throws Exception {
        log.debug("收到消息-> " + functionId + ", reqNum-> " + header.reqNum + ", req->" + req.toString());
        try {
            /**0：否，1：是*/
            int isSendToAll = req.getIsSendToAll();
            String userId = req.getUserId();
            String itemId = req.getItemId();
            JoloGame.JoloGame_GiveGiftsAck.Builder ack = JoloGame.JoloGame_GiveGiftsAck.newBuilder();
            ack.setIsSendToAll(req.getIsSendToAll())
                    .setItemId(req.getItemId())
                    .setResult(1)
                    .setRoomId(req.getRoomId())
                    .setTableId(req.getTableId())
                    .setTargetId(req.getTargetId())
                    .setUserId(userId);
            ItemConfigBean config = ProductionService.getInstance().getGiftConfig(Integer.parseInt(itemId));

            if (config == null) {
                ack.setResult(-2);
                ack.setResultMsg(ErrorCodeEnum.GAME_50052_1.getCode());
                ctx.writeAndFlush(new JoloGame_GiveGiftsAck_50052(ack.build(), header));
                return;
            }

            /**单价*/
            //double price = config.getPrice() / 100d * getTable().getRoomConfig().getAnte() + config.getExtraPrice();
            //double totalPrice = price;

            double price = 0;
            double totalPrice = price;

            AbstractTable table = getTable();
            PlayerInfo player = table.getPlayer(userId);


            //没在桌上
            if (!table.getInGamePlayersByPlayerId().containsKey(userId)) {
                log.info("此玩家没在桌内");
                ack.setResult(-1).setResultMsg(ErrorCodeEnum.GAME_50050_2.getCode());
                ctx.writeAndFlush(new JoloGame_GiveGiftsAck_50052(ack.build(), header));
                return;
            }
            if (null == player) {
                log.info("此玩家没在桌内");
                ack.setResult(-1).setResultMsg(ErrorCodeEnum.GAME_50050_2.getCode());
                ctx.writeAndFlush(new JoloGame_GiveGiftsAck_50052(ack.build(), header));
                return;
            }
            ArrayList<String> playerIds = new ArrayList<>();
            if (isSendToAll == GameConst.IS_SEND_TO_ALL) {
                //单价*除去自己的所有玩家
                int roles = table.getInGamePlayersByPlayerId().size() - 1;
                if (roles <= 0) {
                    log.info("没有找到可送礼玩家");
                    ack.setResult(-1).setResultMsg(ErrorCodeEnum.GAME_50052_2.getCode());
                    ctx.writeAndFlush(new JoloGame_GiveGiftsAck_50052(ack.build(), header));
                    return;
                }
                totalPrice = roles * price;
                playerIds = table.getInGamePlayerIds(userId);
            } else {
                if (!table.getInGamePlayersByPlayerId().containsKey(req.getTargetId())) {
                    log.info("对方已离开");
                    ack.setResult(-1).setResultMsg(ErrorCodeEnum.GAME_50052_3.getCode());
                    ctx.writeAndFlush(new JoloGame_GiveGiftsAck_50052(ack.build(), header));
                    return;
                }
                playerIds.add(req.getTargetId());
            }
            ack.setTargetId(req.getTargetId());//一直都传过来
            if (player.getPlayScoreStore() < totalPrice) {
                log.info("没有足够的积分购买礼物 player.getPlayScoreStore()" +
                        player.getPlayScoreStore() + " totalPrice:" + totalPrice);
                ack.setResult(-1).setResultMsg(ErrorCodeEnum.GAME_50052_4.getCode());
                ctx.writeAndFlush(new JoloGame_GiveGiftsAck_50052(ack.build(), header));
                return;
            }

            if (totalPrice < 0 && config.getItemType() != ItemType.TYPE_GIFT) {
                log.info("价格异常 totalPrice:" + totalPrice);
                ack.setResult(-1).setResultMsg(ErrorCodeEnum.GAME_50052_5.getCode());
                ctx.writeAndFlush(new JoloGame_GiveGiftsAck_50052(ack.build(), header));
                return;
            }
            StringBuilder sb = new StringBuilder();
            sb.append(",扣前玩家积分：" + player.getPlayScoreStore());
            player.minusPlayScoreStore((int) totalPrice, LogReasons.CommonLogReason.GAME_GIFT);
            log.info("减去价格 totalPrice:" + totalPrice + "单价：" + (config.getPrice() / 100) + "底注：" + getTable().getRoomConfig().getAnte() + ",桌内人数：" + table.getInGamePlayers().size()
                    + sb.toString() + ", 扣后玩家积分：" + player.getPlayScoreStore());

            ack.setCurrPlayScore(player.getPlayScoreStore());
            ctx.writeAndFlush(new JoloGame_GiveGiftsAck_50052(ack.build(), header));

            TableLogUtil.gift(functionId, "giveGifts", userId, player.getNickName(), table.getPlayType() + "",
                    table.getRoomId(), table.getTableId(), totalPrice, itemId, config.getPrice(), table.getRoomConfig().getAnte(), config.getExtraPrice(), TableUtil.inGamePlayersBySeatNumToString(table));
            //记录
            //giftRecord(table, userId, playerIds, itemId);

            //发送通知
            NoticeBroadcastMessages.moneyChangeNotice(table,userId,player.getPlayScoreStore());

            Collection<String> targetIds = playerIds;
            NoticeBroadcastMessages.giveGifts(table, userId, req.getIsSendToAll(), req.getItemId(), targetIds);
            //发送玩家送礼日志
            //User user = DBUtil.selectByPrimaryKey(userId);//modify 2018-08-31
            User user = StoredObjManager.hget(RedisConst.USER_INFO.getProfix(), RedisConst.USER_INFO.getField() + userId, User.class);
            LogService.OBJ.sendSendGiftLog(user, "" + config.getId(), config.getItemName(), targetIds.toString(), (long) totalPrice);
            long timeMillis = System.currentTimeMillis() - time;
            if (timeMillis > GameConst.COST_TIME) {
                LoggerUtils.performance.info("GiveGiftsReq_50052,cost time:{},req:{}", timeMillis, req.toString());
            }
        } catch (Exception ex) {
            log.error("SendNotice ERROR：", ex);
        } finally {
            long useTimes = System.currentTimeMillis() - time;
            if(useTimes > 500) {
                log.error("GiveGifts。 耗时->{} 毫秒, reqNum->{}", useTimes, header.reqNum); //TODO:临时增加
            }
        }
    }

    private void giftRecord(AbstractTable tableInfo, String userId, ArrayList<String> targetIds, String itemId) {
        Iterator<String> it1 = targetIds.iterator();
        GiftHistoryModel record = new GiftHistoryModel();
        record.setCount(1);
        record.setGiftItemId(itemId);
        record.setPlayType(1);
        record.setRoomId(tableInfo.getRoomId());
        record.setTableId(tableInfo.getTableId());
        record.setUserId(userId);
        while (it1.hasNext()) {
            String targetId = it1.next();
            record.setTargetUserId(targetId);
            DBUtil.insertGiftHistory(record);
            log.info("add gift record :" + record.toString());
        }

    }
}
